Easy2Siksha.com
Clearly, Binary Search is much faster for large datasets.
Recursive Binary Search Algorithm
Pseudocode
Code
Algorithm BinarySearchRecursive(arr, low, high, key):
1. If low > high:
return -1 // Key not found
2. mid ← (low + high) / 2
3. If arr[mid] = key:
return mid
4. Else if key < arr[mid]:
return BinarySearchRecursive(arr, low, mid - 1, key)
5. Else:
return BinarySearchRecursive(arr, mid + 1, high, key)
End Algorithm
Example Program (C Language)
c
#include <stdio.h>
int binarySearch(int arr[], int low, int high, int key) {
if (low > high) return -1;
int mid = (low + high) / 2;
if (arr[mid] == key) return mid;
else if (key < arr[mid]) return binarySearch(arr, low, mid - 1, key);
else return binarySearch(arr, mid + 1, high, key);
}
int main() {
int arr[] = {5, 12, 18, 23, 45, 67, 89};
int n = sizeof(arr)/sizeof(arr[0]);
int key = 45;
int result = binarySearch(arr, 0, n-1, key);
if (result != -1)
printf("Element found at index %d\n", result);
else
printf("Element not found\n");
return 0;
}
This program demonstrates recursive Binary Search.
Complexity Analysis